package util

import (
	"bytes"
	"strings"
	"text/template"
)

func GetTempText(tmpl string, fields any) (string, error) {
	t, err := template.New("tmpl").
		Funcs(template.FuncMap{
			"CamelToUnderScore": func(t string) string {
				//大驼峰转下划线
				var result string
				for i, c := range t {
					if i > 0 && 'A' <= c && c <= 'Z' {
						result += "_" + strings.ToLower(string(c))
					} else {
						result += strings.ToLower(string(c))
					}
				}
				return result
			},
			"UnderScoreToCamel": func(t string) string {
				//下划线转大驼峰
				var result string
				words := strings.Split(t, "_")
				for _, w := range words {
					if w != "" {
						result += strings.ToUpper(string(w[0])) + w[1:]
					}
				}
				return result
			},
			"Contains": func(s, substr string) bool {
				return strings.Contains(s, substr)
			},
		}).
		Parse(tmpl)
	if err != nil {
		return "", err
	}
	result := bytes.NewBuffer(nil)
	err = t.Execute(result, fields)
	return result.String(), err
}
